'use strict';

module.exports = app => {
  const mongoose = app.mongoose;
  const Schema = mongoose.Schema;

  const WebErrorLogSchema = new Schema({
    /**
     * 日志时间
     */
    date: { type: Date, default: new Date() },
    /**
   * 错误信息
   */
    errMsg: { type: String, default: '' },
    /**
     * 信息
     */
    info: { type: String, default: '' },
    /**
     * 路由
     */
    routerPath: { type: String, default: '' },
    /**
     * 错误信息
     */
    domClass: { type: String, default: '' },
    /**
     * 浏览器型号
     */
    userAgent: { type: String, default: '' },
    /**
     * 用户名
     */
    userName: { type: String, default: '' },
    /**
     * 默认标记
     */
    defaultTag: { type: String, default: '' },
  });

  // eslint-disable-next-line jsdoc/require-param
  /**
   * 获取查询参数
   */
  WebErrorLogSchema.statics.getFindParameter = function(data) {
    const { startDate, endDate, selKey, conditions } = data;
    const params = {
      date: {
        $gte: new Date(startDate),
        $lte: new Date(endDate),
      },
    };
    if (selKey && conditions) {
      params[selKey] = { $regex: conditions, $options: 'i' };
    }
    return params;
  };

  // eslint-disable-next-line jsdoc/require-param
  /**
   * 从回收站还原
   */
  WebErrorLogSchema.statics.listData = function(data) {
    const params = this.getFindParameter(data);
    const { pageSize, pageNum, reverse } = data;
    const field = {};
    const skip = (pageNum - 1) * pageSize;
    const model = this.find(params, field).skip(skip).limit(pageSize);
    model.sort({
      date: reverse === 'true' ? -1 : 1,
    });
    return model.exec();
  };

  WebErrorLogSchema.statics.getCount = function(data) {
    const params = this.getFindParameter(data);
    return this.countDocuments(params);
  };

  /**
   * 删除单个数据
   * @param id 要删除数据的ID
   * @returns {*}
   */
  WebErrorLogSchema.statics.removeModel = function(id) {
    return this.deleteOne({
      _id: mongoose.Types.ObjectId(id),
    });
  };

  return mongoose.model('webErrorLog', WebErrorLogSchema, 'webErrorLogs');
};
